package com.xyzwps.example.moment;

import com.xyzwps.example.data.Trie;

import java.util.List;

public class PatternParser {

    private static final Trie TOKENS = new Trie();

    static {
        TOKENS.add("YYYY");
        TOKENS.add("MM");
        TOKENS.add("DD");
        TOKENS.add("HH");
        TOKENS.add("mm");
        TOKENS.add("ss");
        TOKENS.add("SSS");
    }

    public static ParsedPattern parsePattern(String pattern) {
        var parsed = new ParsedPattern();

        final int len = pattern.length();
        int start = 0;
        for (int i = 0; i < len; ) {
            var result = TOKENS.match(pattern, i);
            if (result.isEmpty()) {
                i++;
                continue;
            }

            var end = result.get(result.size() - 1);
            if (start != i) {
                parsed.add(new Segment.Text(pattern.substring(start, i), start, i));
            }
            parsed.add(new Segment.Token(pattern.substring(i, end), i, end));
            start = i = end;
        }
        if (start != len) {
            parsed.add(new Segment.Text(pattern.substring(start, len), start, len));
        }

        return parsed;
    }

    public static void main(String[] args) {

        List.of(
                        "YYYY-MM-DD",
                        "YYYY-MM-DD HH:mm:ss.SSS",
                        "YYYY-MM-DD HH:mm:ss.SS",
                        " YYYY-MM-DD ",
                        "YYYY年YY月DD日",
                        "YYYYYYY"
                )
                .forEach(p -> {
                    System.out.println("=============================================");
                    System.out.println(p);
                    System.out.println(parsePattern(p));
                    System.out.println();
                });

    }
}
